package com.jframe.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.jframe.cfg.model.DataSrc;
import com.jframe.cfg.model.RoleDatasrc;
import com.jframe.cfg.service.DatasrcService;
import com.jframe.cfg.service.RoledataSrcService;
import com.jframe.sys.controller.utils.BaseAction;
import com.jframe.sys.controller.utils.DicCache;
import com.jframe.sys.controller.utils.QueryHelp;
import com.jframe.sys.controller.utils.TabmCache;
import com.jframe.sys.orm.service.BaseService;
import com.jframe.sys.orm.utils.ResultSet;
import com.jframe.sys.utils.JsonUtil;
import com.jframe.sys.utils.StringUtil;
import com.jframe.sys.webui.Tree;

public class ExtendAction extends BaseAction {

	protected void baseLoad(String SERVICE,Class CLAZZ){
		int start = this.pageInfo.getGridStart(request);
		int limit = this.pageInfo.getGridLimit(request);
		String conditions = StringUtil.null2Space(request.getParameter("conditions"));
		BaseService baseService = (BaseService)this.getBean(SERVICE);		
		QueryHelp queryHelp = new QueryHelp(conditions,CLAZZ);
		ResultSet<Object> rs= baseService.findListByPage(queryHelp,this.conditionFilter(),"",start, limit);
		this.print(JsonUtil.obj2Json(rs));
	}
	
	protected void baseLoad(String SERVICE,Class CLAZZ,String by){
		int start = this.pageInfo.getGridStart(request);
		int limit = this.pageInfo.getGridLimit(request);
		String conditions = StringUtil.null2Space(request.getParameter("conditions"));
		BaseService baseService = (BaseService)this.getBean(SERVICE);		
		QueryHelp queryHelp = new QueryHelp(conditions,CLAZZ);
		ResultSet<Object> rs= baseService.findListByPage(queryHelp,this.conditionFilter(),by,start, limit);
		this.print(JsonUtil.obj2Json(rs));
	}
	
	protected void baseLoad(String SERVICE,Class CLAZZ,String condition,String by){
		int start = this.pageInfo.getGridStart(request);
		int limit = this.pageInfo.getGridLimit(request);
		String conditions = StringUtil.null2Space(request.getParameter("conditions"));
		BaseService baseService = (BaseService)this.getBean(SERVICE);		
		QueryHelp queryHelp = new QueryHelp(conditions,CLAZZ);
		ResultSet<Object> rs= baseService.findListByPage(queryHelp,this.conditionFilter()+condition,by,start, limit);
		this.print(JsonUtil.obj2Json(rs));
	} 
	
	protected void baseLoad(String SERVICE,Class CLAZZ,String condition,String by,Object obj){
		int start = this.pageInfo.getGridStart(request);
		int limit = this.pageInfo.getGridLimit(request);
		String conditions = StringUtil.null2Space(request.getParameter("conditions"));
		BaseService baseService = (BaseService)this.getBean(SERVICE);		
		QueryHelp queryHelp = new QueryHelp(conditions,CLAZZ);
		ResultSet<Object> rs= baseService.findListByPage(queryHelp,this.conditionFilter()+condition,by,obj,start, limit);
		this.print(JsonUtil.obj2Json(rs));
	}
	
	protected void baseLoad(String SERVICE,Class CLAZZ,String condition,String by,Object[] objs){
		int start = this.pageInfo.getGridStart(request);
		int limit = this.pageInfo.getGridLimit(request);
		String conditions = StringUtil.null2Space(request.getParameter("conditions"));
		BaseService baseService = (BaseService)this.getBean(SERVICE);		
		QueryHelp queryHelp = new QueryHelp(conditions,CLAZZ);
		ResultSet<Object> rs= baseService.findListByPage(queryHelp,this.conditionFilter()+condition,by,objs,start, limit);
		this.print(JsonUtil.obj2Json(rs));
	}
	
	protected void baseSave(String SERVICE,Class CLAZZ){
		Map<String,Object> map = new HashMap<String, Object>();
		String objstr = this.request.getParameter("obj");
		Object obj = JsonUtil.json2Obj(objstr,CLAZZ);
		obj = beforeSave(obj);
		BaseService baseService = (BaseService)this.getBean(SERVICE);
		try{
			baseService.save(obj);
			afterSave(obj);	
			map.put("result", true);
			map.put("obj", obj);			
		}catch(Exception e){
			map.put("result", false);
		}		
		this.print(JsonUtil.map2Json(map));
	}
	
	protected void baseDelete(String SERVICE){
		String ids = this.request.getParameter("ids");
		BaseService baseService = (BaseService)this.getBean(SERVICE);	
		baseService.del(ids);
		afterDelete(ids);
		this.print("true");
	}
	
	protected Object getObject(String SERVICE){
		BaseService baseService = (BaseService)this.getBean(SERVICE);
		int id=StringUtil.parseInt(request.getParameter("id"));
		if(id>0){
			Object obj = baseService.load(id);
			return obj;
		}else{
			return new Object();
		}
	}

	public void makeIndexTree(){
		String iframeId = this.pageInfo.getPageIframeId(request);	
		String datasrcId = this.pageInfo.getDataSrcId(request);
		String tabId = this.pageInfo.getPageTabId(request);
		DatasrcService dataSrcService = (DatasrcService)this.getBean("dataSrcService");
		DataSrc dataSrc = null;
		if(StringUtil.null2Space(datasrcId).equals("0")||StringUtil.null2Space(datasrcId).equals("")){
			dataSrc	= dataSrcService.getDataSrcTreeIndex(iframeId, tabId); //手动叶签和伪叶签
		}else{
			dataSrc	= dataSrcService.load(StringUtil.parseInt(datasrcId));//字典叶签
		}
		if(!StringUtil.null2Space(dataSrc.getDatasrc()).equals("")){
			String treeSrc = TabmCache.getCombotreeJson(dataSrc.getDatasrc());
			if(dataSrc.getIsValidate()==1&&!treeSrc.equals("")){//需要校验
				RoledataSrcService roledataSrcService = (RoledataSrcService)this.getBean("roledataSrcService");
				RoleDatasrc roleDataSrc = roledataSrcService.getRoleDatasrcByProperties(this.getCurUser().getRoleId(), iframeId,dataSrc.getTabId(), dataSrc.getId());
				String[] keys = StringUtil.null2Space(roleDataSrc.getDatasrcIds()).split(",");
				List<Map> list = json2ListMap(treeSrc,keys);				
				this.print(JsonUtil.list2Json(list));
			}else{
				this.print(treeSrc);
			}
		}else{
			this.print("");
		}				
	}
	
	
	
	protected Object beforeSave(Object object){		
		return object; 
	}
	
	protected void afterSave(Object object){
		
	}
	
	protected void afterDelete(String ids){
		
	}
		
	
	private String conditionFilter(){
		StringBuffer condition = new StringBuffer();
		String iframeId = this.pageInfo.getPageIframeId(request);	
		String tabId = this.pageInfo.getPageTabId(request);	
		if(!tabId.equals("")&&!iframeId.equals("")){
			DatasrcService dataSrcService = (DatasrcService)this.getBean("dataSrcService");
			List<DataSrc> list = dataSrcService.findListByProperties(iframeId,"");
			for(DataSrc datasrc:list){
				if(datasrc.getType()==3){
					condition.append(" and ");
					condition.append(datasrc.getFieldname());
					condition.append("=");
					condition.append(tabId);
				}else if(datasrc.getIsValidate()==1){
					//查询所有权限						
					RoledataSrcService roledataSrcService = (RoledataSrcService)this.getBean("roledataSrcService");
					RoleDatasrc roleDataSrc = roledataSrcService.getRoleDatasrcByProperties(this.getCurUser().getRoleId(), iframeId,tabId, datasrc.getId());
					if(!StringUtil.null2Space(roleDataSrc.getDatasrcIds()).equals("")){
						condition.append(" and ");
						condition.append(datasrc.getFieldname());
						condition.append(" in ");					
						condition.append("("+roleDataSrc.getDatasrcIds()+")");
					}else{
						condition.append(" and 1=2 "); //不分配任何权限
					}
				}else if(datasrc.getType()==2){
					condition.append(" and ");
					condition.append(datasrc.getFieldname());
					condition.append(" in ");
					condition.append("("+this.cacheJson2ids(DicCache.getComboboxJson(datasrc.getDatasrc()))+")");
				}
			}
		}
		return condition.toString();		
	}
	
	private boolean isKeyIn(String key,String[] keys){
		boolean isin = false;
		for(String id:keys){
			if(id.equals(key)){
				isin=true;
				break;
			}
		}
		return isin;
	}
	
	/**
     * 将缓存中的json转换为List<map>
     * @param jsonStr
     * @return
     */
    private  List<Map> json2ListMap(String jsonStr,String[] keys){
    	List<Map> list = new ArrayList<Map>();
    	JSONArray jsonArray = JSONArray.fromObject(jsonStr);
    	for(int i = 0 ; i<jsonArray.size(); i++){   
    		JSONObject jsonObject = jsonArray.getJSONObject(i);   		
    		 String id = jsonObject.getString("id");
    		 if(isKeyIn(id,keys)){
    			 Map map = new HashMap();
    			 map.put("id", id);
    			 map.put("text", jsonObject.getString("text"));
    			 try{
	    			 String children = StringUtil.null2Space(jsonObject.getString("children"));
	    			 map.put("children", json2ListMap(children,keys)); 	    			
    			 }catch(Exception e){}
    			 list.add(map);  			 
    		 }
    	}
    	return list;
    }
    
    private String cacheJson2ids(String json){
		List<Tree> list = JsonUtil.json2List(json, Tree.class);
		String ids = "";
		for(Tree tree:list){
			ids +=tree.getId()+",";
		}
		if(list.size()>0){
			ids=ids.substring(0,ids.length()-1);
		}
		return ids;
	}
	
}
